<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\workWechat;

use app\common\model\platform\PlatformSetting;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Message;
use hiduoke\services\workWechat\kf\Messenger;
use think\facade\Log;

trait WorkWechatKfService
{
    protected $kfConfig = null;

    /**
     * @var \EasyWeChat\Work\Application
     */
    protected $kfApp = null;

    /**
     * 获取微信客服配置
     * @return array
     */
    public function getKfConfig()
    {
        $servicer = (new PlatformSetting())->getValueByKey("servicer", $this->plaid);
        $config = [
            'corp_id' => $this->corp_id,
            'secret'  => $servicer['secret'] ?? '',
            'token'   => $servicer['token'] ?? '',
            'aes_key' => $servicer['aes_key'] ?? '',
            'log'     => [
                'default'  => 'error', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    'error' => [
                        'driver' => 'single',
                        'path'   => '/tmp/easywechat/work_wechat_error.log',
                        'level'  => 'error',
                    ],
                ],
            ],
        ];
        return $config;
    }

    /**
     * 获取客服APP
     * @param $config array 配置
     * @return \EasyWeChat\OpenWork\Work\Application|\EasyWeChat\Work\Application|null
     */
    public function getKfApp($config = [])
    {
        if ($this->auth_type == 'open') {
            // 服务商授权获取App
            $this->openApp = (new WorkWechatOpen())->getOpenApp();
            return $this->openApp->work($this->corp_id, $this->platform['config']['permanent_code']);
        } else {
            // 手动配置
            if ($this->kfApp) {
                return $this->kfApp;
            }
            if (!$config) {
                $this->kfConfig = $this->getKfConfig();
            } else {
                $this->kfConfig = $config;
            }
            $this->kfApp = Factory::work($this->kfConfig);
            return $this->kfApp;
        }
    }

    /**
     * 发送消息
     * @param Message $message
     * @param string $touser
     * @param string $open_kfid
     * @return Messenger
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function kfMessage(Message $message = null, $touser = "", $open_kfid = "")
    {
        $messenger = new Messenger($this->getKfApp()->kf_message);
        if ($message) {
            $messenger->message($message);
        }
        if ($touser) {
            $messenger->toUser($touser);
        }
        if ($open_kfid) {
            $messenger->toKfId($open_kfid);
        }
        return $messenger;
    }

    /**
     * 客户基本信息获取
     * @param string|array $external_userid_list
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function kfBatchget($external_userid_list)
    {
        $params = [
            "external_userid_list" => $external_userid_list,
        ];
        return $this->getKfApp()->kf_message->httpPostJson('cgi-bin/kf/customer/batchget', $params);
    }


    public function getLastMsg($message, $next_cursor, $limit = 10)
    {
        $token = $message['Token'];
        $params = ['cursor' => $next_cursor ?? '', 'token' => $token, 'limit' => $limit, 'open_kfid' => $message['OpenKfId']];
        $msg = $this->getKfApp()->kf_message->httpPostJson('cgi-bin/kf/sync_msg', $params);
        if ($msg['errcode'] == 0) {
            $new_next_cursor = $msg['next_cursor'];
            //判断消息是否解析正确
            if ($msg['has_more'] == 0) {
                $last_msg = end($msg['msg_list']);
                if (!$last_msg) {
                    return $this->getLastMsg($token, '', 1000);
                }
                $msg['msg_list'] = array(0 => $last_msg);
                return $msg;
            } else {
                return $this->getLastMsg($token, $new_next_cursor, 1000);
            }
        } else {
            return $msg;
        }
    }
}
